<template>
  <view class="c-textarea relative zIndex10 h100p">
    <textarea
      v-model="inputValue"
      :hold-keyboard="true"
      resize="vertical"
      :class="['disb flex1 fs24',className]"
      :maxlength="max"
      :disabled="disabled"
      :placeholder="placeholder"
      :placeholder-class="placeholderClass"
      @blur="onBlur"
    ></textarea>
    <view v-if="showCount" class="count fs24 fw400">
      字数
      {{ count }}
    </view>
  </view>
</template>

<script>
export default {
  name: 'c-textarea',
  props: {
    max: {
      type: Number,
      default: 0,
    },
    value: {
      type: String,
      default: '',
    },
    placeholder: {
      type: String,
      default: '',
    },
    placeholderClass: {
      type: String,
      default: '',
    },
    showCount: {
      type: Boolean,
      default: false,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    className: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      inputValue: '',
      count: 0,
    };
  },
  watch: {
    value: function (val) {
      this.inputValue = val;
    },
    inputValue(val) {
      if (val == null) return;
      this.count = val.length;
      this.$emit('input', val);
    },
  },
  created() {
    this.inputValue = this.value;
  },
  methods: {
    onBlur() {
      if (this.max > 0) {
        const inputValue = this.inputValue;
        const len = inputValue.length;
        if (len > this.max) {
          const value = this.inputValue.slice(0, this.max);
          this.inputValue = value;
        }
      }
    },
  },
};
</script>

<style lang="less" scoped>
.c-textarea {
  textarea {
    height: 100%;
    width: 100%;
  }
}

.count {
  color: rgba(59, 59, 60, 1);
  position: absolute;
  right: 0;
  bottom: 0;
}
</style>
